package com.kedacom.ctsp.authz.oauth2.configuration;

import lombok.extern.slf4j.Slf4j;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.FlywayException;
import org.flywaydb.core.api.configuration.ClassicConfiguration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;

/**
 * @remark
 * @authorfenghaiju
 * @Date 2018/11/219:05
 **/
@Configuration
@Slf4j
public class FlyWayConfiguration implements CommandLineRunner {
    @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;

    @Value("${sharding.jdbc.datasource.url}")
    private String shardingUrl;
    @Value("${sharding.jdbc.datasource.username}")
    private String shardingUsername;
    @Value("${sharding.jdbc.datasource.password}")
    private String shardingassword;

    @Override
    public void run(String... strings) throws Exception {
        migrateRbac();
        migrateProject();
    }

    public void migrateRbac() {

        Flyway flyway = Flyway.configure().dataSource(url, username, password).load();
        try {

            flyway.migrate();

        } catch (FlywayException e) {

            flyway.repair();

            e.printStackTrace();

        }

    }

    public void migrateProject() {
        Flyway flyway = Flyway.configure().locations("classpath:db/migration1").dataSource(shardingUrl, shardingUsername, shardingassword).load();
        try {

            flyway.migrate();

        } catch (FlywayException e) {

            flyway.repair();

            e.printStackTrace();

        }

    }
}
